import React, { useState, useEffect } from 'react'
import { Card, Row, Col, Statistic, Table, Tag, Space, Typography, Spin } from 'antd'
import {
  EyeOutlined,
  LikeOutlined,
  CommentOutlined,
  ShareAltOutlined,
  UserOutlined,
  RiseOutlined,
  FallOutlined,
  MinusOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import RadarChart from '../../components/Charts/RadarChart'
import LineChart from '../../components/Charts/LineChart'
import BarChart from '../../components/Charts/BarChart'
import PieChart from '../../components/Charts/PieChart'
import { PlatformMetrics } from '../../../types/mediaData'
import {
  generateMockPlatformMetrics,
  generateTimeSeriesData,
  generateDataOverview,
  PLATFORM_META
} from '../../../services/mock/mediaDataMock'

const { Title, Paragraph } = Typography

/**
 * 融媒数据分析页面
 * 展示多平台数据分析和可视化
 */
const MediaAnalyticsPage: React.FC = () => {
  const [loading, setLoading] = useState(true)
  const [platformData, setPlatformData] = useState<PlatformMetrics[]>([])

  useEffect(() => {
    // 模拟数据加载
    setTimeout(() => {
      const data = generateMockPlatformMetrics()
      setPlatformData(data)
      setLoading(false)
    }, 500)
  }, [])

  if (loading) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100%',
        minHeight: '400px'
      }}>
        <Spin size="large" tip="加载数据中..." />
      </div>
    )
  }

  const overview = generateDataOverview(platformData)
  const timeSeriesData = generateTimeSeriesData(30)

  // 雷达图数据
  const radarData = platformData.slice(0, 4).map(p => ({
    name: p.platformName,
    value: [
      p.views / 10000,
      p.likes / 1000,
      p.comments / 100,
      p.shares / 100,
      p.engagementRate * 1000
    ],
    color: PLATFORM_META[p.platform].color
  }))

  const radarIndicators = [
    { name: '播放量(万)', max: 120 },
    { name: '点赞数(千)', max: 60 },
    { name: '评论数(百)', max: 120 },
    { name: '分享数(百)', max: 60 },
    { name: '互动率(‰)', max: 150 }
  ]

  // 折线图数据 - 只显示播放量趋势
  const lineChartSeries = timeSeriesData
    .filter(s => s.metric === '播放量')
    .map(s => ({
      name: s.platformName,
      data: s.data,
      color: PLATFORM_META[s.platform].color
    }))

  // 柱状图数据 - 各平台播放量对比
  const barChartData = platformData.map(p => ({
    name: p.platformName,
    value: p.views,
    color: PLATFORM_META[p.platform].color
  }))

  // 饼图数据 - 流量占比
  const pieChartData = platformData.map(p => ({
    name: p.platformName,
    value: p.views,
    color: PLATFORM_META[p.platform].color
  }))

  // 表格列定义
  const columns: ColumnsType<PlatformMetrics> = [
    {
      title: '平台',
      dataIndex: 'platformName',
      key: 'platformName',
      render: (text: string, record: PlatformMetrics) => (
        <Tag color={PLATFORM_META[record.platform].color}>{text}</Tag>
      )
    },
    {
      title: '播放量',
      dataIndex: 'views',
      key: 'views',
      sorter: (a, b) => a.views - b.views,
      render: (value: number) => value.toLocaleString()
    },
    {
      title: '点赞数',
      dataIndex: 'likes',
      key: 'likes',
      sorter: (a, b) => a.likes - b.likes,
      render: (value: number) => value.toLocaleString()
    },
    {
      title: '评论数',
      dataIndex: 'comments',
      key: 'comments',
      sorter: (a, b) => a.comments - b.comments,
      render: (value: number) => value.toLocaleString()
    },
    {
      title: '分享数',
      dataIndex: 'shares',
      key: 'shares',
      sorter: (a, b) => a.shares - b.shares,
      render: (value: number) => value.toLocaleString()
    },
    {
      title: '粉丝数',
      dataIndex: 'followers',
      key: 'followers',
      sorter: (a, b) => a.followers - b.followers,
      render: (value: number) => value.toLocaleString()
    },
    {
      title: '互动率',
      dataIndex: 'engagementRate',
      key: 'engagementRate',
      sorter: (a, b) => a.engagementRate - b.engagementRate,
      render: (value: number) => (value * 100).toFixed(2) + '%'
    },
    {
      title: '趋势',
      dataIndex: 'trend',
      key: 'trend',
      filters: [
        { text: '上升', value: 'up' },
        { text: '稳定', value: 'stable' },
        { text: '下降', value: 'down' }
      ],
      onFilter: (value, record) => record.trend === value,
      render: (trend: string, record: PlatformMetrics) => {
        const icons = {
          up: <RiseOutlined style={{ color: '#52c41a' }} />,
          down: <FallOutlined style={{ color: '#f5222d' }} />,
          stable: <MinusOutlined style={{ color: '#faad14' }} />
        }
        const colors = {
          up: '#52c41a',
          down: '#f5222d',
          stable: '#faad14'
        }
        return (
          <Space>
            {icons[trend as keyof typeof icons]}
            <span style={{ color: colors[trend as keyof typeof colors] }}>
              {record.changeRate !== undefined && Math.abs(record.changeRate).toFixed(1) + '%'}
            </span>
          </Space>
        )
      }
    }
  ]

  return (
    <div style={{
      padding: '32px 48px',
      height: '100%',
      overflow: 'auto',
      background: '#f5f5f5'
    }}>
      {/* 页面标题 */}
      <div style={{ marginBottom: 32 }}>
        <Title level={2} style={{ marginBottom: 8 }}>融媒数据分析</Title>
        <Paragraph type="secondary" style={{ fontSize: 16 }}>
          多平台内容数据可视化分析，基于模拟数据展示
        </Paragraph>
      </div>

      {/* 数据概览卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} lg={8} xl={4}>
          <Card hoverable>
            <Statistic
              title="总播放量"
              value={overview.totalViews}
              prefix={<EyeOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={8} xl={4}>
          <Card hoverable>
            <Statistic
              title="总点赞数"
              value={overview.totalLikes}
              prefix={<LikeOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={8} xl={4}>
          <Card hoverable>
            <Statistic
              title="总评论数"
              value={overview.totalComments}
              prefix={<CommentOutlined />}
              valueStyle={{ color: '#faad14' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={8} xl={4}>
          <Card hoverable>
            <Statistic
              title="总分享数"
              value={overview.totalShares}
              prefix={<ShareAltOutlined />}
              valueStyle={{ color: '#f5222d' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={8} xl={4}>
          <Card hoverable>
            <Statistic
              title="总粉丝数"
              value={overview.totalFollowers}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} lg={8} xl={4}>
          <Card hoverable>
            <Statistic
              title="平均互动率"
              value={(overview.avgEngagementRate * 100).toFixed(2)}
              suffix="%"
              valueStyle={{ color: '#13c2c2' }}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} lg={12}>
          <Card title="平台数据雷达图" variant="borderless">
            <RadarChart
              data={radarData}
              indicators={radarIndicators}
              height={400}
            />
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="流量分布占比" variant="borderless">
            <PieChart
              data={pieChartData}
              height={400}
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24}>
          <Card title="30天播放量趋势" variant="borderless">
            <LineChart
              series={lineChartSeries}
              height={400}
              yAxisName="播放量"
            />
          </Card>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24}>
          <Card title="各平台播放量对比" variant="borderless">
            <BarChart
              data={barChartData}
              height={350}
              yAxisName="播放量"
            />
          </Card>
        </Col>
      </Row>

      {/* 数据详情表格 */}
      <Card title="数据详情" variant="borderless">
        <Table
          columns={columns}
          dataSource={platformData}
          rowKey="platform"
          pagination={false}
          scroll={{ x: 1200 }}
        />
      </Card>
    </div>
  )
}

export default MediaAnalyticsPage
